# _*_ coding:utf-8 _*_
# By:赵先宇
import os
import traceback
from .base import BasePlugin
from lib.response import BaseResponse
from lib.logger import logger

class CPU(BasePlugin):
    def win(self, handler, hostname=None):
        pass

    def linux(self, handler, hostname):
        # linux 执行命令
        response = BaseResponse()
        try:
            if self.debug:
                with open(os.path.join(self.base_dir, 'files', 'cpuinfo.out')) as f:
                    ret = f.read()
            else:
                    ret = handler.cmd('cat /proc/cpuinfo', hostname)
            response.data = self.parse(ret)
        except Exception as e:
            response.status = False
            error_msg = traceback.format_exc()
            response.error = error_msg
            logger.error(error_msg)  # 错误信息记录日志
        return response.dict


    @staticmethod
    def parse(content):
        """
        解析shell命令返回结果
        :param content: shell 命令结果
        :return:解析后的结果
        """
        response = {'cpu_count': 0, 'cpu_physical_count': 0, 'cpu_model': ''}

        cpu_physical_set = set()  # 创建一个无序不重复元素集合
        content = content.strip()
        for item in content.split('\n\n'):
            for row_line in item.split('\n'):
                key, value = row_line.split(':')
                key = key.strip()
                if key == 'processor':
                    response['cpu_count'] += 1  # CPU 核心个数
                elif key == 'physical id':
                    cpu_physical_set.add(value)  # CPU 物理个数
                elif key == 'model name':
                    if not response['cpu_model']:
                        response['cpu_model'] = value  # CPU 型号
        response['cpu_physical_count'] = len(cpu_physical_set)  # CPU 物理个数
        return response



